package com.itjiange.reglg.interceptor;

import com.itjiange.reglg.common.ErrorCode;
import com.itjiange.reglg.common.RedisCode;
import com.itjiange.reglg.constant.UserConstant;
import com.itjiange.reglg.exception.BussinessException;
import com.itjiange.reglg.utils.NetUtils;
import com.itjiange.reglg.utils.RedisUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 *
 * @author ItJiange
 * @date 2023/11/22
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取 ip 地址
        String ipAddress = NetUtils.getIpAddress(request);
        // 将 ip 地址当做 key 存入 Redis 中
        String redisKeyByIP = UserConstant.USER_LOGIN_STATE.concat(ipAddress);
        if (!redisUtils.ifHasKey(redisKeyByIP)) {
            redisUtils.setKV(redisKeyByIP, "1", 10 * 60);
            return true;
        }
        String blackIP = redisUtils.getValueByKey(redisKeyByIP);
        if (RedisCode.BLACK_IP.getPrefix().equals(blackIP)) {
            throw new BussinessException(ErrorCode.FORBIDDEN_ERROR, "你小心输错 5 次了，一天后再试试吧哈哈");
        }
        // 次数加一
        redisUtils.addOne(redisKeyByIP, 10 * 60);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 获取 ip 地址
        String ipAddress = NetUtils.getIpAddress(request);
        // 将 ip 地址当做 key 存入 Redis 中
        String redisKeyByIP = UserConstant.USER_LOGIN_STATE.concat(ipAddress);
        String userLogin = (String) request.getAttribute(UserConstant.USER_LOGIN_STATE);
        // 获取登录失败次数
        String failLoginCount = redisUtils.getValueByKey(redisKeyByIP);
        int count = Integer.parseInt(failLoginCount);
        // 获取 ip 地址
        if (count > 1 && UserConstant.USER_LOGIN_SUCCESS.equals(userLogin)) {
            redisUtils.setKV(redisKeyByIP, "1", 10 * 60);
        }
        // 登录失败五次后拉黑 1 天
        if (count >= 5) {
            redisUtils.setKV(redisKeyByIP, RedisCode.BLACK_IP.getPrefix(), 60 * 60 * 24);
        }
    }
}
